package com.geek.service.impl;

import com.geek.exception.InventoryManager;
import com.geek.exception.StockException;
import com.geek.mapper.MarketGoodsProductMapper;
import com.geek.model.MarketCart;
import com.geek.model.MarketGoodsProduct;
import com.geek.service.GoodsProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wbw
 * @data 2024/06/17 21:58
 **/
@Service
public class GoodsProductServiceImpl implements GoodsProductService {
    @Autowired
    MarketGoodsProductMapper goodsProductMapper;
    @Override
    public void updateNumByCartList(List<MarketCart> cartList) {
        for (MarketCart cart : cartList) {
            this.updateNumByCart(cart);
        }
    }

    @Override
    public void updateNumByCart(MarketCart marketCart) {
        Integer productId = marketCart.getProductId();
        Integer number = (int)marketCart.getNumber();
        MarketGoodsProduct marketGoodsProduct = goodsProductMapper.selectByPrimaryKey(productId);
        Integer productNumber = marketGoodsProduct.getNumber();
        Integer newNumber = productNumber - number;
        InventoryManager inventoryManager = new InventoryManager(productNumber);
        try {
            // 尝试检查库存是否足够
            inventoryManager.checkStock(number); // 正常情况
        } catch (StockException e) {
            // 处理库存不足的异常
            System.err.println(e.getMessage());
        }
        marketGoodsProduct.setNumber(newNumber);
        goodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct);
    }
}
